<template>
  <el-dialog
    :title="title"
    :model-value="modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    width="600px"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="日程标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入日程标题" />
      </el-form-item>
      
      <el-form-item label="日程类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择日程类型">
          <el-option
            v-for="item in Object.values(dict.SCHEDULE_TYPE)"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="优先级" prop="priority">
        <el-select v-model="form.priority" placeholder="请选择优先级">
          <el-option
            v-for="item in Object.values(dict.PRIORITY_LEVEL)"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择状态">
          <el-option
            v-for="item in Object.values(dict.SCHEDULE_STATUS)"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="时间范围" prop="timeRange">
        <el-date-picker
          v-model="form.timeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>

      <el-form-item label="地点" prop="location">
        <el-input v-model="form.location" placeholder="请输入地点" />
      </el-form-item>

      <el-form-item label="参与者" prop="participants">
        <el-select
          v-model="form.participants"
          multiple
          filterable
          placeholder="请选择参与者"
        >
          <el-option
            v-for="item in userList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="提醒时间" prop="reminder">
        <el-select v-model="form.reminder" placeholder="请选择提醒时间">
          <el-option label="不提醒" value="0" />
          <el-option label="5分钟前" value="5" />
          <el-option label="15分钟前" value="15" />
          <el-option label="30分钟前" value="30" />
          <el-option label="1小时前" value="60" />
          <el-option label="2小时前" value="120" />
        </el-select>
      </el-form-item>

      <el-form-item label="日程内容" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          rows="4"
          placeholder="请输入日程内容"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="$emit('update:modelValue', false)">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        确 定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { createSchedule, updateSchedule } from '@/api/schedule'
import { getUserList } from '@/api/user'
import dict from '@/constants/dictionary'

const props = defineProps({
  modelValue: Boolean,
  title: String,
  formData: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

// 表单数据
const formRef = ref(null)
const loading = ref(false)
const form = reactive({
  title: '',
  type: '',
  priority: '0',
  status: '0',
  timeRange: [],
  location: '',
  participants: [],
  reminder: '0',
  content: ''
})

// 表单校验规则
const rules = {
  title: [{ required: true, message: '请输入日程标题', trigger: 'blur' }],
  type: [{ required: true, message: '请选择日程类型', trigger: 'change' }],
  timeRange: [{ required: true, message: '请选择时间范围', trigger: 'change' }],
  content: [{ required: true, message: '请输入日程内容', trigger: 'blur' }]
}

// 用户列表
const userList = ref([])

// 获取用户列表
const fetchUserList = async () => {
  try {
    const res = await getUserList()
    userList.value = res.data.map(user => ({
      label: user.userName,  // 显示名称
      value: user.userId     // 用户ID
    }))
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 组件挂载时获取用户列表
onMounted(() => {
  fetchUserList()
})

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    const data = {
      ...form,
      startTime: form.timeRange[0],
      endTime: form.timeRange[1]
    }
    delete data.timeRange

    if (props.formData.id) {
      data.id = props.formData.id
      await updateSchedule(data.id, data)
    } else {
      await createSchedule(data)
    }

    ElMessage.success('保存成功')
    emit('success')
    emit('update:modelValue', false)
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    loading.value = false
  }
}

// 监听表单数据变化
watch(
  () => props.formData,
  (val) => {
    if (val.id) {
      // 编辑模式，需要处理数据字典的值
      const formData = {
        ...val,
        timeRange: [val.startTime, val.endTime]
      }
      
      // 确保类型和优先级的值是字符串类型
      formData.type = String(val.type || '')
      formData.priority = String(val.priority || '0')
      formData.status = String(val.status || '0')

      // 设置表单数据
      Object.assign(form, formData)

      // 添加调试日志
      console.log('编辑表单数据:', {
        原始数据: val,
        处理后数据: form,
        类型选项: Object.values(dict.SCHEDULE_TYPE),
        优先级选项: Object.values(dict.PRIORITY_LEVEL)
      })
    } else {
      // 新建模式，使用默认值
      Object.assign(form, {
        title: '',
        type: '',
        priority: '0',
        status: '0',
        timeRange: [],
        location: '',
        participants: [],
        reminder: '0',
        content: ''
      })
    }
  },
  { immediate: true }
)
</script>

<style scoped>
.el-dialog {
  :deep(.el-input__wrapper),
  :deep(.el-textarea__inner),
  :deep(.el-select__wrapper) {
    background-color: var(--bg-primary);
    box-shadow: 0 0 0 1px var(--border-color);
  }

  :deep(.el-input__wrapper.is-focus),
  :deep(.el-textarea__inner:focus),
  :deep(.el-select__wrapper.is-focus) {
    box-shadow: 0 0 0 1px var(--primary-color);
  }

  :deep(.el-input__wrapper:hover),
  :deep(.el-textarea__inner:hover),
  :deep(.el-select__wrapper:hover) {
    box-shadow: 0 0 0 1px var(--primary-color);
  }

  :deep(.el-select-dropdown) {
    background-color: var(--bg-primary);
    border: 1px solid var(--border-color);
  }

  :deep(.el-select-dropdown__item) {
    color: var(--text-primary);
  }

  :deep(.el-select-dropdown__item.hover),
  :deep(.el-select-dropdown__item:hover) {
    background-color: var(--bg-secondary);
  }

  :deep(.el-date-editor) {
    background-color: var(--bg-primary);
  }

  :deep(.el-date-range-picker) {
    background-color: var(--bg-primary);
    
    .el-date-range-picker__content {
      background-color: var(--bg-primary);
    }
    
    .el-date-table th,
    .el-date-table td {
      background-color: var(--bg-primary);
    }
  }

  :deep(.el-form-item__label) {
    color: var(--text-secondary);
  }
}
</style> 